//
//  DateModel.swift
//  ToDoList
//
//  Created by Qingke on 16/4/15.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class DateModel: NSObject {
    
    var categories: [Category]
    let categoryIndex = "categoryIndex"
    let FirstTimeKey = "FirstTime"

    //虚拟变量
    var selectedCategoryIndex: Int {
        set {
            NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: categoryIndex) //赋值时调用这个方法
        }
        get {
            return NSUserDefaults.standardUserDefaults().integerForKey(categoryIndex)

        }
    }
    override init() {
        //1初始化自己的变量
        categories = [Category]()
        //2调用super.init
        super.init()
        print(dataFilePath())
        //3调用其他方法
        loadCategory()
        setdefaultValues()
        handFirstTime()
    }
    //保存文件的目录
    func dataFilePath() ->String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let filePath = path[0] as NSString
        return filePath.stringByAppendingPathComponent("CategoryDataList.plist")
    }
    //保存文件的方法
    func saveCategoryList() {
        //1，创建data对象
        let data = NSMutableData()
        //2，把数据写入到data对象中
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(categories, forKey: "CategoryDataList")
        archiver.finishEncoding()
        //3，把data对象写入到文件
        data.writeToFile(dataFilePath(), atomically: true)
    }
    //下载文件的方法
    func loadCategory() {
        let data = NSData(contentsOfFile: dataFilePath())
        if let data = data{
            let unarckiver = NSKeyedUnarchiver(forReadingWithData: data)
            categories = unarckiver.decodeObjectForKey("CategoryDataList") as! [Category]
            unarckiver.finishDecoding()
            sortCategory()
        }
    }
    
    
    func setdefaultValues() {
        let defaultValue = [categoryIndex:-1,FirstTimeKey:true]
        NSUserDefaults.standardUserDefaults().registerDefaults(defaultValue)
    }
    
    //记录是不是第一次
    
    func handFirstTime() {
        let FirstTime = NSUserDefaults.standardUserDefaults().boolForKey(FirstTimeKey)
        if FirstTime {
            
            let category = Category(name: "工作")
            let task = Task()
            task.name = "学习iOS开发"
            category.tasks.append(task)
            categories.append(category)
            
            selectedCategoryIndex = 0
            
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: FirstTimeKey)
            //强制现在就写到文件中
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }
    
    //对category排序的功能 属于数据
    
    func sortCategory() {
        categories.sortInPlace({
            c1,c2
            in return
            c1.name.localizedStandardCompare(c2.name) == .OrderedAscending  //descnding
        })
    }
}














